import { NextResponse, type NextRequest } from 'next/server'; import { physicalCheckoutEnabled, physicalCheckoutPausedMessage } from '@/app/lib/free-studio-checkout'; import { commerceDb } from '@/app/lib/commerce-db'; import { stripe } from '@/app/lib/stripe'; import { env } from '@/app/lib/env'; import { displayOrderId } from '@/app/lib/orders'; import { SHIPPING_COUNTRIES } from '@/app/lib/shipping'; // POST /api/orders/[id]/checkout // ------------------------------------------------------------------ // Creates a Stripe Checkout Session for the customer's commission AT // SUBMIT TIME (not at design-approval time). The Builder's "Continue to // payment" button routes the customer to /checkout, /checkout calls // /api/orders to create the order row, then calls this endpoint to mint // the Stripe session, then redirects to the Stripe-hosted page. // // On successful Stripe payment, the webhook (app/api/webhooks/stripe) // transitions the order from pending_payment → pending_design and // sends the magic-link email so the customer can track their order. // // This is intentionally NOT auth-gated (the customer hasn't completed // magic-link login yet at submit time); it relies on Stripe's metadata // orderId for downstream linking. Anyone with an orderId could trigger // session creation, but they'd just be paying for someone else's // commission — non-harmful. export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function POST( req: NextRequest, ctx: { params: Promise<{ id: string }> }, ) { if (!physicalCheckoutEnabled()) { return NextResponse.json({ error: physicalCheckoutPausedMessage, studio: '/studio' }, { status: 503, headers: { 'Cache-Control': 'no-store' }, }); } const { id } = await ctx.params; // termsAccepted is the customer's explicit consent to the refund // policy shown on /checkout. Required to mint a Stripe session — we // also persist the timestamp on the order row for auditability. let body: { email?: string; termsAccepted?: boolean }; try { body = await req.json(); } catch { return NextResponse.json({ error: 'invalid json' }, { status: 400 }); } if (body.termsAccepted !== true) { return NextResponse.json( { error: 'You must accept the refund policy and terms to continue.' }, { status: 400 }, ); } const admin = commerceDb(); const { data: order, error: fetchErr } = await admin .from('orders') .select('id, user_email, status, price_cents, config, stripe_session_id') .eq('id', id) .single(); if (fetchErr || !order) { return NextResponse.json({ error: 'order not found' }, { status: 404 }); } if ( order.status !== 'pending_payment' && order.status !== 'pending_design' && order.status !== 'abandoned' ) { // pending_design is allowed for backwards-compat (legacy flow). // abandoned is allowed for the resume-payment flow: customer // returns to a stale order via /checkout?orderId=…&canceled=1 // and re-pays. We transition them back to pending_payment so // the Stripe webhook handler (which only matches pending_payment) // can move them forward normally. return NextResponse.json( { error: `cannot start checkout from status ${order.status}` }, { status: 409 }, ); } if (order.status === 'abandoned') { await admin.from('orders').update({ status: 'pending_payment' }).eq('id', id); } // Record terms acceptance before creating the Stripe session. await admin.from('orders').update({ terms_accepted_at: new Date().toISOString(), }).eq('id', id); const cfg = (order.config ?? {}) as { productId?: string; size?: string; styleId?: string }; const session = await stripe().checkout.sessions.create({ mode: 'payment', payment_method_types: ['card'], line_items: [{ price_data: { currency: 'usd', unit_amount: order.price_cents, // tax_behavior is REQUIRED when automatic_tax is enabled. // 'exclusive' = our advertised price is pre-tax; Stripe Tax // computes FL state + county surtax (and any other registered // jurisdiction) and adds it on top at checkout. tax_behavior: 'exclusive', product_data: { name: `Lumen & Gesso commission · ${displayOrderId(order.id)}`, description: `${cfg.styleId ?? 'custom'} · ${cfg.productId ?? ''} ${cfg.size ?? ''}`.trim(), // Generic tangible goods tax category. Stripe's default works // for framed art / canvas — taxable in jurisdictions that // tax tangible personal property. Override only if FL or // another jurisdiction ever flags this as the wrong category. tax_code: 'txcd_99999999', }, }, quantity: 1, }], customer_email: order.user_email, // Stripe's type expects a mutable AllowedCountry[]; SHIPPING_COUNTRIES // is `as const` so we shallow-copy to satisfy the assignment. shipping_address_collection: { allowed_countries: [...SHIPPING_COUNTRIES] }, // Stripe Tax: computes the right rate per delivery address. Uses // the shipping address Stripe collects above (or the billing // address on the card) and applies whichever registered // jurisdiction matches. Returns zero tax for addresses in // jurisdictions where we have no registration. // // Note: `customer_update` is intentionally omitted — it requires a // pre-existing `customer` parameter, which we don't have on a // first-time guest checkout (we only have `customer_email`). // automatic_tax still works fine with just the shipping address // the customer enters at checkout. automatic_tax: { enabled: true }, metadata: { orderId: order.id }, payment_intent_data: { metadata: { orderId: order.id }, // NOTE: intentionally NO receipt_email. Stripe's auto-receipt is // account-level ("Receipt from Protomota, LLC", shared with Jotley). // We send our own fully Lumen & Gesso-branded receipt from the // checkout.session.completed webhook instead (receiptHtml). }, success_url: `${env.site.url()}/login/check-email?orderId=${order.id}&email=${encodeURIComponent(order.user_email)}&paid=1`, cancel_url: `${env.site.url()}/checkout?orderId=${order.id}&canceled=1`, }); await admin.from('orders').update({ stripe_session_id: session.id }).eq('id', id); if (!session.url) return NextResponse.json({ error: 'no checkout url' }, { status: 500 }); return NextResponse.json({ url: session.url }); }